<?php
class PlayersController extends AppController {

	public function main($id = null) {
		
		if ( $id == null ) {
			
			$this->redirect('/players/listing');
			
		}
		
		$this->request->data = $this->Player->findById($id);
		//pr($this->request->data);
		
	}
	
	public function listing() {
		
		$players = $this->Player->find('all');
		$this->set('players', $players);
				
	}
	
	public function upload_stats( $pID = null ) {

		//Check access to upload stats for Player
		//Check for post

		ini_set('auto_detect_line_endings',TRUE);
		
		$filename = TMP . 'Workbook1.csv';
		$delimiter=',';
		$header = NULL;
	    $data = array();
		//echo "before";
	    if (($handle = fopen($filename, 'r')) !== FALSE)
	    {
	        while (($row = fgetcsv($handle, 0, $delimiter)) !== FALSE)
	        {
	            if(!$header)
	                $header = $row;
	            else
	                $data[] = array_combine($header, $row);
	        }
	        fclose($handle);
	    }
		
		//pr($data);
		$this->loadModel('Stat');
		
		$this->Stat->begin();
		
		foreach ($data as $stat_line) {
		
			$this->Stat->create();
			$this->Stat->set('player_id', $pID);

            //$this->Stat->set('player_id', $stat_line['LeagueName']);
            //$this->Stat->set('player_id', $stat_line['YearConference']);
            $this->Stat->set('game_date', $stat_line['GameDate']);
            //$this->Stat->set('player_id', $stat_line['OpposingTeam']);
            //$this->Stat->set('player_id', $stat_line['PlayerName']);
            //$this->Stat->set('player_id', $stat_line['Pts']);
            $this->Stat->set('2pt_field_goal_attempt', $stat_line['2ptFGA']);
            $this->Stat->set('2pt_field_goal_made', $stat_line['2ptFGM']);
            $this->Stat->set('3pt_field_goal_attempt', $stat_line['3ptFGA']);
            $this->Stat->set('3pt_field_goal_made', $stat_line['3ptFGM']);
            $this->Stat->set('free_throw_attempt', $stat_line['FTA']); 
            $this->Stat->set('free_throw_made', $stat_line['FTM']); 
            $this->Stat->set('offensive_rebounds', $stat_line['OffReb']); 
            $this->Stat->set('defensive_rebounds', $stat_line['DefReb']);
            $this->Stat->set('assists', $stat_line['Asst']); 
            $this->Stat->set('steals', $stat_line['Stls']); 
            $this->Stat->set('blocks', $stat_line['Blks']); 
            $this->Stat->set('personal_fouls', $stat_line['PersonalFouls']); 
            $this->Stat->set('technical_fouls', $stat_line['TechnicalFouls']); 
            $this->Stat->set('turnovers', $stat_line['Turnovers']);
            $this->Stat->set('minutes', $stat_line['MinutesPlayed']); 
			
			$this->Stat->save();

		}

		$this->Stat->commit();
		

	}
	
	public function manager_roster() {
		
		//TODO add condition to only show players created by Manager
		$players = $this->Player->find('all');
		
		$this->set('players', $players);
	
		
	}

}
?>